<template>
  <transition name="confirm-fade">
    <div class="confirm" v-show="showFlag">
      <div class="confirm-wrapper">
        <div class="confirm-content">
          <p class="text">{{ title }}</p>
          <div class="operate" @click.stop>
            <div class="operate-btn left" @click="cancel">
              {{ cancelBtnText }}
            </div>
            <div class="operate-btn" @click="confirm">
              {{ ConfirmBtnText }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  data() {
    return {
      showFlag: false,
      title: "确认清空所有历史纪录吗?", // 可以使用props
      ConfirmBtnText: "确定", // 为什么不用props接受参数
      cancelBtnText: "取消", // 之后会明白
    };
  },
  methods: {
    show(cb) {
      // 加入一个在执行Promise前的回调
      this.showFlag = true;
      typeof cb === "function" && cb.call(this, this);
      return new Promise((resolve, reject) => {
        // 返回Promise
        this.reject = reject; // 给取消按钮使用
        this.resolve = resolve; // 给确认按钮使用
      });
    },
    cancel() {
      this.reject("cancel"); // 抛个字符串
      this.hide();
    },
    confirm() {
      this.resolve("confirm");
      this.hide();
    },
    hide() {
      this.showFlag = false;
      document.body.removeChild(this.$el); // 结束移除Dom
      this.$destroy(); // 执行组件销毁
    },
  },
};
</script>

<style scoped lang="less">
.confirm {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 998;
  background-color: rgba(0, 0, 0, 0.3);

  &.confirm-fade-enter-active {
    animation: confirm-fadein 0.3s;

    .confirm-content {
      animation: confirm-zoom 0.3s;
    }
  }

  .confirm-wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;

    .confirm-content {
      width: 270px;
      border-radius: 13px;
      background: #fff;

      .text {
        padding: 19px 15px;
        line-height: 22px;
        text-align: center;
        font-size: 18px;
        // color: rgba(255, 255, 255, 0.5);
        color: #333;
      }

      .operate {
        display: flex;
        align-items: center;
        text-align: center;
        font-size: 18px;

        .operate-btn {
          flex: 1;
          line-height: 22px;
          padding: 10px 0;
          border-top: 1px solid rgba(0, 0, 0, 0.3);
          // color: rgba(255, 255, 255, 0.3);
          color: #333;
          cursor: pointer;

          &.left {
            border-right: 1px solid rgba(0, 0, 0, 0.3);
          }
        }
        .operate-btn:hover {
          color: red;
        }
      }
    }
  }
}

@keyframes confirm-fadein {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

@keyframes confirm-zoom {
  0% {
    transform: scale(0);
  }

  50% {
    transform: scale(1.1);
  }

  100% {
    transform: scale(1);
  }
}
</style>